package com.gec.anan.customer.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gec.anan.customer.mapper.CustomerInfoMapper;
import com.gec.anan.customer.mapper.CustomerLoginLogMapper;
import com.gec.anan.customer.service.CustomerInfoService;
import com.gec.anan.model.entity.customer.CustomerInfo;
import com.gec.anan.model.entity.customer.CustomerLoginLog;
import com.gec.anan.model.form.customer.UpdateWxPhoneForm;
import com.gec.anan.model.vo.customer.CustomerLoginVo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    //依賴WxMaService
    @Autowired
    WxMaService wxMaService;

    //依賴CustomerInfoMapper
//    @Autowired
//    CustomerInfoMapper customerInfoMapper;

    //依賴CustomerInfoMapper
    @Autowired
    CustomerLoginLogMapper customerLoginLogMapper;

    /**
     * 授权登录
     * @param code
     * @return
     */
    @Override
    public Long login(String code) {
        String openid = null;
        //1、调用微信接口判断有没有会话
        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            //2、获取openid、判断当前的账户是否已经在业务【已经注册】
            openid = sessionInfo.getOpenid();
            //2-1：日志记录。。。。。。
        } catch (Exception e) {
            e.printStackTrace();
            //2-2：抛出自定义异常。。。。
        }
        //--查询用户信息
        CustomerInfo customerInfo = this.getOne(
                new LambdaQueryWrapper<CustomerInfo>()
                        .eq(CustomerInfo::getWxOpenId, openid)
        );
        //3、如果没有注册：新增到用户记录表
        if(customerInfo==null){
            customerInfo = new CustomerInfo();
            customerInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            customerInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            customerInfo.setWxOpenId(openid);
            //新增
            this.save(customerInfo);
        }
        //4、如果已经注册、记录登錄日志
        CustomerLoginLog customerLoginLog = new CustomerLoginLog();
        customerLoginLog.setCustomerId(customerInfo.getId());
        customerLoginLog.setMsg("小程序登录");
        //新增日志记录
        customerLoginLogMapper.insert(customerLoginLog);
        //5、返回用户id
        return customerInfo.getId();
    }

    /**
     * 获取客户登录信息
     * @param customerId
     * @return
     */
    @Override
    public CustomerLoginVo getCustomerLoginInfo(Long customerId) {
        //获取用户信息并转换为VO
        CustomerInfo customerInfo = this.getById(customerId);
        CustomerLoginVo customerInfoVo = new CustomerLoginVo();
        BeanUtils.copyProperties(customerInfo, customerInfoVo);
        //判断是否绑定手机号码，如果未绑定，小程序端发起绑定事件
        Boolean isBindPhone = StringUtils.hasText(customerInfo.getPhone());
        customerInfoVo.setIsBindPhone(isBindPhone);
        return customerInfoVo;
    }

    /**
     * 更新乘客手机号码
     * @param updateWxPhoneForm
     * @return
     */
    @SneakyThrows
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
        // 调用微信 API 获取用户的手机号
        WxMaPhoneNumberInfo phoneInfo = wxMaService.getUserService().getPhoneNoInfo(updateWxPhoneForm.getCode());
        String phoneNumber = phoneInfo.getPhoneNumber();
        log.info("phoneInfo:{}", JSON.toJSONString(phoneInfo));

        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setId(updateWxPhoneForm.getCustomerId());
        customerInfo.setPhone(phoneNumber);
        return this.updateById(customerInfo);
    }
}
